package com.atrix.CinemaView.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.atrix.CinemaView.dao.FileDao;
import com.atrix.CinemaView.exception.ParamErrorException;
import com.atrix.CinemaView.pojo.Container;
import com.atrix.CinemaView.pojo.FileObj;
import com.atrix.CinemaView.pojo.dto.info.MdInfo;
import com.atrix.CinemaView.pojo.dto.MdStreamData;
import com.atrix.CinemaView.service.MdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MdServiceImpl implements MdService {
    @Autowired
    private FileDao fileDao;
    
    @Override
    public List<MdInfo> getInfo() {
        return fileDao.getMdInfoList();
    }
    
    @Override
    public MdStreamData getRandomMd() {
        List<Container<FileObj>> mdContainerList = fileDao.getMdContainerList();
        int containerIndex = RandomUtil.randomInt(mdContainerList.size());
        int index = RandomUtil.randomInt(mdContainerList.get(containerIndex).getSize());
        return new MdStreamData(mdContainerList.get(containerIndex).getData().get(index));
    }
    
    @Override
    public MdStreamData getRandomMdInContainer(int containerIndex) {
        List<Container<FileObj>> mdContainerList = fileDao.getMdContainerList();
        if (containerIndex < 0 || containerIndex >= mdContainerList.size()) {
            throw new ParamErrorException();
        }
        int index = RandomUtil.randomInt(mdContainerList.get(containerIndex).getSize());
        return new MdStreamData(mdContainerList.get(containerIndex).getData().get(index));
    }
    
    @Override
    public MdStreamData getMd(int containerIndex, int index) {
        List<Container<FileObj>> mdContainerList = fileDao.getMdContainerList();
        if (containerIndex < 0 || containerIndex >= mdContainerList.size()) {
            throw new ParamErrorException();
        }
        if (index < 0 || index >= mdContainerList.get(containerIndex).getSize()) {
            throw new ParamErrorException();
        }
        return new MdStreamData(mdContainerList.get(containerIndex).getData().get(index));
    }
}
